package cn.sdormitory.smartdor.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.sdormitory.basedata.dao.BDeviceDao;
import cn.sdormitory.basedata.dao.BDormitoryDao;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.dto.DeviceWithDor;
import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.service.BClassService;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.basedata.service.BStudentService;
import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.common.utils.SmsSendTemplate;
import cn.sdormitory.common.utils.StringUtils;
import cn.sdormitory.smartdor.dao.SdAttenceDao;
import cn.sdormitory.smartdor.dao.SdWeekendAttenceDao;
import cn.sdormitory.smartdor.entity.OriginalRecord;
import cn.sdormitory.smartdor.entity.SdAttence;
import cn.sdormitory.smartdor.entity.SdDevice;
import cn.sdormitory.smartdor.entity.SdWeekendAttence;
import cn.sdormitory.smartdor.service.OriginalRecordService;
import cn.sdormitory.smartdor.service.SdAttenceService;
import cn.sdormitory.smartdor.service.SdDeviceService;
import cn.sdormitory.smartdor.vo.DormitoryAttenceVo;
import cn.sdormitory.smartdor.vo.SdAttenceVo;
import cn.sdormitory.sys.dao.SysConfigDao;
import cn.sdormitory.sys.entity.SysConfig;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.service.SysDictDetailService;
import cn.sdormitory.sys.service.SysUserService;
import cn.sdormitory.sysset.entity.SyssetSmsTemplate;
import cn.sdormitory.sysset.service.SyssetAttenceRuleService;
import cn.sdormitory.sysset.service.SyssetSmsTemplateService;
import cn.sdormitory.wx.entity.WechatPushMessage;
import cn.sdormitory.wx.mapper.WechatPushMessageMapper;
import cn.sdormitory.wx.utils.WXUtil;
import cn.sdormitory.wx.utils.WeatherDataCreator;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created By ruanteng
 * DateTime：2020/11/27
 */
@Slf4j
@Service("sdAttenceServiceImpl")
public class SdAttenceServiceImpl extends ServiceImpl<SdAttenceDao, SdAttence> implements SdAttenceService {
    
    private static final String dormitory_clock_template_id = "sSf9OX_udYCbmHuBMd8GM4neA9DcyPuzLSGQyop5PQA";

    @Autowired
    private BStudentService bStudentService;

    @Autowired
    private BStudentDao bStudentDao;

    @Autowired
    private OriginalRecordService originalRecordService;

    @Autowired
    private BClassService bClassService;

    @Autowired
    private SyssetSmsTemplateService syssetSmsTemplateService;

    @Autowired
    private SyssetAttenceRuleService syssetAttenceRuleService;

    @Autowired
    private BDormitoryService bDormitoryService;
    
    @Autowired
    WeatherDataCreator weatherDataCreator;
    
    @Resource
    private WechatPushMessageMapper wechatPushMessageMapper;
    
    @Autowired
    WXUtil wxUtil;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SdDeviceService sdDeviceService;
    @Autowired
    private SysDictDetailService sysDictDetailService;

    @Autowired
    private BDeviceDao deviceDao;

    @Autowired
    private SysConfigDao sysConfigDao;

    @Resource
    private SdAttenceDao sdAttenceDao;
    
    @Resource
    private SdWeekendAttenceDao sdWeekendAttenceDao;

    @Autowired
    private BDormitoryDao bDormitoryDao;

    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public CommonPage<SdAttence> getPage(Map<String, Object> params) {
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));
        String dateStr = String.valueOf(params.get("checkDate"));
        if ("null".equals(dateStr)) {
            dateStr = null;
        }
        List<SdAttence> list = this.baseMapper.getList(dateStr, (pageNum - 1) * pageSize, pageSize);

        CommonPage commonPage = CommonPage.getCommonPage(pageNum, pageSize, this.baseMapper.getListCount(dateStr), list);

        return commonPage;


    }

    @Override
    public void create() throws ParseException {
        List<OriginalRecord> list = originalRecordService.getListByDate();
        System.out.println("-----------------   "+list+"   ----------------"+list.size());
//        list.stream().forEach(a -> {
//            SdDevice sdDevice = sdDeviceService.getDeviceNo(a.getDeviceNo());
//            try {
//                //判断今天是否需要考勤
//                if (syssetAttenceRuleService.getByAttenceRuleByTime(new Date(),sdDevice.getAttenceRuleId().intValue()) != null)
//                    return;
//            } catch (ParseException exception) {
//                exception.printStackTrace();
//            }
//            if (sdDevice.getAttenceRuleId()==null || sdDevice.getAttenceRuleId()<=0) {
//                //如果考勤规则为空则不考勤
//            } else {
//                SyssetAttenceRule syssetAttenceRule = syssetAttenceRuleService.getSyssetAttenceRuleById(sdDevice.getAttenceRuleId());
//                //按考勤规则来判断今天是否考勤
//                if (!syssetAttenceRule.getAttenceDay().contains(String.valueOf(DateTimeUtils.dateTimeFormat(System.currentTimeMillis()).getDay()))){
//                    return;
//                }
//                BStudent bStudent = bStudentService.getByStudentNo(a.getStudentNo());
//                if (bStudent == null)
//                    return;
//                SdAttence sdAttence = new SdAttence();
//                if (a.getAccessDate() == null) {
//                    //没有考勤信息则发送短信给家长，班主任，宿管
//                    //查询对应的短信模板
//                    SyssetSmsTemplate syssetSmsTemplate = syssetSmsTemplateService.getBySmsTypee(CommonConstant.SMS_TEMPLATE_TYPE_ATTENCE);
//                   //获取对应的宿舍信息
//                    SysDictDetail sysDictDetail=sysDictDetailService.getDetailByTypeAndValue("sys_building",bStudent.getBuildingNo());
//                    SysDictDetail sysDictDetail1=sysDictDetailService.getDetailByTypeAndValue("sys_storey",bStudent.getStorey());
//                    // if (CommonConstant.ATTENDANCE_COMEBACKLATE.equals(a.getAttenceStatus())) {
//                        String text = syssetSmsTemplate.getSmsContent().replace(CommonConstant.SMS_TEMPLATE_STR, bStudent.getClassName()+"学号："+bStudent.getStudentNo()+"姓名："+bStudent.getStudentName()+"宿舍："+sysDictDetail.getDictLabel()+sysDictDetail1.getDictLabel()+bStudent.getDormitoryNo());
//                        BClass bClass = bClassService.getBClassById(bStudent.getClassId());
//                        BDormitory bDormitory = bDormitoryService.getBDormitoryById(Long.valueOf(bStudent.getBdormitoryId()));
//                        SysUser sysUser = sysUserService.getUserById(bClass.getClassTeacherId());
//                        SysUser sysUser1 = sysUserService.getUserById(bDormitory.getId());
//                        SmsSendTemplate.sms(bStudent.getPhone(), text);
//                        SmsSendTemplate.sms(sysUser.getPhone(), text);
//                        SmsSendTemplate.sms(sysUser1.getPhone(), text);
//                        SmsSendTemplate.sms(bStudent.getParentPhone(), text);
//                   // }
//                } else {
//                    sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_NOMAL);
//                    sdAttence.setCreateTime(new Date());
//                    sdAttence.setStudentNo(a.getStudentNo());
//                    sdAttence.setDeviceNo(a.getDeviceNo());
//                    sdAttence.setAccessDate(a.getAccessDate());
//                    this.baseMapper.insert(sdAttence);
//                }
//
//            }
        list.stream().forEach(a -> {
            BStudent bStudent = bStudentService.getByStudentNo(a.getStudentNo());
            if (a.getAccessDate() == null) {
                //判断在考勤表中是否有数据
                if(this.baseMapper.selectAttenceByStudentCount(bStudent.getStudentNo())==0){
                    //判断在考勤表中是否有数据
                    //没有考勤信息则发送短信给家长，班主任，宿管
                    //查询对应的短信模板
                    SyssetSmsTemplate syssetSmsTemplate = syssetSmsTemplateService.getBySmsTypee(CommonConstant.SMS_TEMPLATE_TYPE_ATTENCE);
                    //获取对应的宿舍信息
                    SysDictDetail sysDictDetail=sysDictDetailService.getDetailByTypeAndValue("sys_building",bStudent.getBuildingNo());
                    SysDictDetail sysDictDetail1=sysDictDetailService.getDetailByTypeAndValue("sys_storey",bStudent.getStorey());
                    String text = syssetSmsTemplate.getSmsContent().replace(CommonConstant.SMS_TEMPLATE_STR, bStudent.getClassName()+"学号："+bStudent.getStudentNo()+"姓名："+bStudent.getStudentName()+"宿舍："+sysDictDetail.getDictLabel()+sysDictDetail1.getDictLabel()+bStudent.getDormitoryNo());
                    BClass bClass = bClassService.getBClassById(bStudent.getClassId());
                    BDormitory bDormitory = bDormitoryService.getBDormitoryById(Long.valueOf(bStudent.getBdormitoryId()));
                    SysUser sysUser = sysUserService.getUserById(bClass.getClassTeacherId());
                    SysUser sysUser1 = sysUserService.getUserById(bDormitory.getDormitoryTeacherId());
                    SmsSendTemplate.sms(bStudent.getPhone(), text);
                    SmsSendTemplate.sms(sysUser.getPhone(), text);
                    SmsSendTemplate.sms(sysUser1.getPhone(), text);
                    SmsSendTemplate.sms(bStudent.getParentPhone(), text);
               }

            } else {
                if(this.baseMapper.selectAttenceByStudentCount(bStudent.getStudentNo())==0){

                    SdDevice sdDevice = sdDeviceService.getDeviceNo(a.getDeviceNo());
                    try {
                        //判断今天是否需要考勤
//                    if (syssetAttenceRuleService.getByAttenceRuleByTime(new Date(),sdDevice.getAttenceRuleId().intValue()) != null)
//                        return;
                        if (syssetAttenceRuleService.getByAttenceRuleByTime(a.getAccessDate(),sdDevice.getAttenceRuleId().intValue()) == null) {
                            return;
                        }
                    } catch (ParseException exception) {
                        exception.printStackTrace();
                    }
//                if (sdDevice.getAttenceRuleId()==null || sdDevice.getAttenceRuleId()<=0) {
//                    //如果考勤规则为空则不考勤
//                } else {
//                    SyssetAttenceRule syssetAttenceRule = syssetAttenceRuleService.getSyssetAttenceRuleById(sdDevice.getAttenceRuleId());
//                    //按考勤规则来判断今天是否考勤
//                    if (!syssetAttenceRule.getAttenceDay().contains(String.valueOf(DateTimeUtils.dateTimeFormat(System.currentTimeMillis()).getDay()))){
//                        return;
//                    }
                    if (bStudent == null) {
                        return;
                    }
                    SdAttence sdAttence = new SdAttence();
                    sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_NOMAL);
                    sdAttence.setCreateTime(new Date());
                    sdAttence.setStudentNo(a.getStudentNo());
                    sdAttence.setDeviceNo(a.getDeviceNo());
                    sdAttence.setAccessDate(a.getAccessDate());
                    this.baseMapper.insert(sdAttence);
                }
                }
//            }
        });
    }

    @Override
    public int delete(String[] id) {
        int count = 0;
        try {
            count = this.baseMapper.deleteBatchIds(Arrays.asList(id));
        } catch (Exception e) {
            e.printStackTrace();
            count = 0;
        }
        return count;

    }

    @Override
    public int getCount(Map<String, Object> params) {
        String dateStr = String.valueOf(params.get("checkDate"));
        if ("null".equals(dateStr)) {
            dateStr = null;
        }
        int count = this.baseMapper.getListCount(dateStr);
        return count;
    }


    @Override
    public int insert(SdAttence sdAttence) {
        return this.baseMapper.insert(sdAttence);
    }


    @Override
    public CommonPage<SdAttenceVo> listAbsenceStudent(Map<String,Object> map) {
        //2.0版本人工考勤
//        if(new Date().getHours()<22&& (map.get("checkDate") == null||map.get("checkDate") == "")){
//            Calendar cal= Calendar.getInstance();
//            cal.add(Calendar.DATE,-1);
//            Date d=cal.getTime();
//            map.put("checkDate",d);
//        }
        //2.0版本人工考勤
        if(map.get("checkDate") == null||map.get("checkDate") == ""){
            map.put("checkDate",simpleDateFormat.format(new Date()));
        }

        List<SdAttenceVo> list = this.baseMapper.listAbsenceStudent(map);
        CommonPage<SdAttenceVo> commonPage = new CommonPage<>();
        commonPage.setList(list);
        return  commonPage;
    }

    @Override
    public CommonPage<SdAttenceVo> listLeaveStudent(Map<String,Object> map) {
        if(map.get("checkDate") == null||map.get("checkDate") == ""){
            map.put("checkDate",simpleDateFormat.format(new Date()));
        }

        List<SdAttenceVo> list = this.baseMapper.listLeaveStudent(map);
        CommonPage<SdAttenceVo> commonPage = new CommonPage<>();
        commonPage.setList(list);
        return  commonPage;
    }

    @Override
    public CommonPage<DormitoryAttenceVo> listAbsenceDormitory(Map<String, Object> map) {
//        if (new Date().getHours() < CommonConstant.ATTENDANCE_TIME_INT && (map.get("checkDate") == null || map.get("checkDate") == "")) {
//            Calendar cal = Calendar.getInstance();
//            cal.add(Calendar.DATE, -1);
//            Date d = cal.getTime();
//            map.put("checkDate", d);
//
//        }
        //2.0版本人工考勤
        if(map.get("checkDate") == null||map.get("checkDate") == ""){
            map.put("checkDate",simpleDateFormat.format(new Date()));
        }
        List<DormitoryAttenceVo> list = this.baseMapper.dormitoryAttenceVos(map);
        CommonPage<DormitoryAttenceVo> commonPage = new CommonPage<>();
        commonPage.setList(list);
        return commonPage;
    }

    @Override
    public void statisticsLackStu() {
        SyssetSmsTemplate syssetSmsTemplate = syssetSmsTemplateService.getBySmsTypee(CommonConstant.SMS_TEMPLATE_TYPE_ATTENCE);
        List<SdAttenceVo> list = this.getLackStu();
        list.stream().forEach(a -> {
            BStudent bStudent = bStudentService.getByStudentNo(a.getStudentNo());
            SdAttence sdAttence = new SdAttence();
            sdAttence.setStudentNo(a.getStudentNo());
            sdAttence.setAttenceStatus(CommonConstant.ATTENDANCE_ABSENCE);
            //增加缺勤时间(当天)
            Date date = new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            sdAttence.setAccessDate(new Date());
            this.baseMapper.insert(sdAttence);
            String text = syssetSmsTemplate.getSmsContent().replace(CommonConstant.SMS_TEMPLATE_STR, bStudent.getStudentName());
            BClass bClass = bClassService.getBClassById(bStudent.getClassId());
            BDormitory bDormitory = bDormitoryService.getBDormitoryById(Long.valueOf(bStudent.getBdormitoryId()));
            SysUser sysUser = sysUserService.getUserById(bClass.getClassTeacherId());
            SysUser sysUser1 = sysUserService.getUserById(bDormitory.getDormitoryTeacherId());

            //学生本人
            SmsSendTemplate.sms(bStudent.getPhone(), text);
            //班主任
            SmsSendTemplate.sms(sysUser.getPhone(), text);
            //宿管
            SmsSendTemplate.sms(sysUser1.getPhone(), text);
            //家长
            SmsSendTemplate.sms(bStudent.getParentPhone(), text);
        });
    }

    @Override
    public List<SdAttenceVo> getLackStu() {
        return this.baseMapper.getLackStu();
    }

    @Override
    public SdAttence getCombacklate(String studentNo, String accessDate) {
        return this.baseMapper.getCombacklate(studentNo,accessDate);
    }

    @Override
    public int update(Long id, SdAttence sdAttence) {
        sdAttence.setId(id);
        return this.baseMapper.updateById(sdAttence);
    }

    @Override
    public int deleteByStuNoAndADate(String studentNo, String accessDate) {
        return this.baseMapper.deleteByStuNoAndADate(studentNo,accessDate);
    }

    @Override
    public int getAttByDateAndStuNoCount(String studentNo, String accessDate) {
        return this.baseMapper.getAttByDateAndStuNoCount(studentNo,accessDate);
    }

    @Override
    public boolean receiveSdAttendanceRecords(List<Map<String, String>> records) throws Exception{
        log.info("......start......");
        log.info(JSON.toJSONString(records));
        long begin = System.currentTimeMillis();
        //提交数据列表
        List<SdAttence> sdAttendanceList = new ArrayList<>();
        
        List<SdWeekendAttence> sdWeekendAttences = new ArrayList<>();
        //所有学生数据
        List<BStudent> allStudent = bStudentDao.getAllStudent();
        //所有宿舍考勤机信息
        List<DeviceWithDor> allDorDeviceList = deviceDao.getAllDeviceWithSd();
        //宿舍考勤规则
        LambdaQueryWrapper<SysConfig> sdAttenceRulesWrapper = new LambdaQueryWrapper<>();
        sdAttenceRulesWrapper.eq(SysConfig::getParamKey,"attendance.dormitory.rules");
        SysConfig sdAttenceRules = sysConfigDao.selectOne(sdAttenceRulesWrapper);
        
        // 周末考勤规则
        LambdaQueryWrapper<SysConfig> sdWeekendRulesWrapper = new LambdaQueryWrapper<>();
        sdWeekendRulesWrapper.eq(SysConfig::getParamKey,"dormitory.weekend.rules");
        SysConfig sdWeekendRules = sysConfigDao.selectOne(sdWeekendRulesWrapper);
        String[] attendanceWeekendRange = sdWeekendRules.getParamValue().split("-");
        String weekendStartTime = attendanceWeekendRange[0];
        String weekendEndTime = attendanceWeekendRange[1];
        
        //考勤迟到范围
//        LambdaQueryWrapper<SysConfig> lateRangeWrapper = new LambdaQueryWrapper<>();
//        lateRangeWrapper.eq(SysConfig::getParamKey,"attendance.late.range");
//        SysConfig lateRange = sysConfigDao.selectOne(lateRangeWrapper);

        for(Map<String,String> map : records){
            log.info("=====> 开始同步宿舍考勤数据...");
            String date = map.get("stuTime");
            String stuId = map.get("userId");
            String serialNo = map.get("deviceCode");
            String facePhoto = map.get("snapFtpUrl");

            if(StringUtils.isEmpty(date)){
                log.info("日期为空");
                continue;
            }
            if(StringUtils.isEmpty(stuId)){
                log.info("学生ID为空");
                continue;
            }
            if(StringUtils.isEmpty(serialNo)){
                log.info("序列号为空");
                continue;
            }

            log.info("当前学生信息：" + stuId + "，考勤时间：" + date + "，打卡设备：" + serialNo);

            //匹配是否存在此学生，根据手机号码匹配
            BStudent stu = null;
            for (int i = 0; i < allStudent.size(); i++) {
                if(String.valueOf(stuId).equals(String.valueOf(allStudent.get(i).getId()))){
                    stu = allStudent.get(i);
                    break;
                }
            }
            if(stu == null){
                log.info("找不到此学生");
                log.info("=====> 结束...");
                continue;
            }

            //判断当前学生是否在指定自己对应宿舍楼层打卡
            boolean isMatch = false;
            //学生所在楼栋
            String buildingNo = stu.getBuildingNo();
            //学生所在楼层
            String storey = stu.getStorey();
            for (int i = 0; i < allDorDeviceList.size(); i++) {
                //查询当前学生是否有匹配的楼栋和楼层
                if(allDorDeviceList.get(i).getBuildingNo().equals(buildingNo)
                    && allDorDeviceList.get(i).getStorey().equals(storey)){
                    //当前学生所在楼栋楼层和当前数据序列号匹配
                    if(serialNo.equals(allDorDeviceList.get(i).getSerialNo())){
                        isMatch = true;
                        break;
                    }
                }
            }
            if(!isMatch){
                log.info("该学生未在指定考勤机打卡");
                log.info("=====> 结束...");
                continue;
            }

            //获取宿舍考勤规则
            SdAttence sdAttence = new SdAttence();
            String accessDate = date.split(" ")[0];

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            sdAttence.setAccessDate(format.parse(date));
            sdAttence.setMendCardPhoto(facePhoto);
            
            if(sdAttenceRules.getParamValue() == null){
                log.info("找不到宿舍考勤规则，请去参数中配置");
                log.info("=====> 结束...");
                continue;
            }

            String[] attendanceRange = sdAttenceRules.getParamValue().split("-");
            String status = judgeAttendanceStatus(date,attendanceRange[0],attendanceRange[1], weekendStartTime, weekendEndTime);
            //状态为-1代表既不是正常打卡也不是迟到打卡，则进入下一次循环
            if("-1".equals(status)){
                log.info("该学生未在指定时间打卡");
                log.info("=====> 结束...");
                continue;
            }else if ("1".equals(status)){
                //当前学生已经存在，则判断当前学生是不是多次打卡，多次打卡则只取其中一次记录
                boolean isRepeat = false;
                if(sdAttendanceList.size() > 0 || sdAttendanceList != null){
                    for (int i = 0; i < sdAttendanceList.size(); i++) {
                        if(stu.getStudentNo().equals(sdAttendanceList.get(i).getStudentNo())){
                            isRepeat = true;
                            break;
                        }
                    }
                }
                if(isRepeat){
                    log.info("该学生重复打卡");
                    log.info("=====> 结束...");
                    continue;
                }
                sdAttence.setStudentNo(stu.getStudentNo());
                // 1正常 2未归寝
                sdAttence.setDeviceNo("考勤机");
                sdAttence.setAttenceStatus("1");
                sdAttence.setBdormitoryId(stu.getBdormitoryId());
                sdAttence.setBuildingNo(stu.getBuildingNo());
                sdAttence.setStorey(stu.getStorey());
                sdAttence.setDormitoryNo(stu.getDormitoryNo());
                sdAttence.setFlag("2");
                sdAttence.setCreateTime(DateUtil.parseDateTime(date));
                // 根据学号以及考勤时间判断考勤表中是否有存在的记录
                List<SdAttence> attenceList = sdAttenceDao.getAttenceByDateAndStudentNo(accessDate,sdAttence.getStudentNo());
    
                if(attenceList == null || attenceList.size() < 1) {
                    sdAttendanceList.add(sdAttence);
                    // 推送宿舍考勤的信息给家长
                    try {
                        pushWxMessageToParent(stu, sdAttence);
                    } catch (Exception e) {
                        log.info("=====> 微信推送消息失败...");
                    }
                    log.info("=====> 正常打卡，结束...");
                }else {
                    log.info("=====> 数据库中存在当前学生当日已打卡记录，结束...");
                }
            } else if ("2".equals(status)) {
                // TODO 如果不在周末则不需要统计数据
                //当前学生已经存在，则判断当前学生是不是多次打卡，多次打卡则只取其中一次记录
                boolean isRepeat = false;
                if(sdWeekendAttences.size() > 0 || sdWeekendAttences != null){
                    for (int i = 0; i < sdWeekendAttences.size(); i++) {
                        if(stu.getStudentNo().equals(sdWeekendAttences.get(i).getStudentNo())){
                            isRepeat = true;
                            break;
                        }
                    }
                }
                if(isRepeat){
                    log.info("该学生重复打卡");
                    log.info("=====> 结束...");
                    continue;
                }
                // 周末考勤
                SdWeekendAttence weekendAttence = new SdWeekendAttence();
                weekendAttence.setDeviceNo("考勤机");
                weekendAttence.setAccessDate(format.parse(date));
                weekendAttence.setStudentNo(stu.getStudentNo());
                weekendAttence.setAttenceStatus("1");
                weekendAttence.setBdormitoryId(stu.getBdormitoryId());
                weekendAttence.setBuildingNo(stu.getBuildingNo());
                weekendAttence.setStorey(stu.getStorey());
                weekendAttence.setDormitoryNo(stu.getDormitoryNo());
                weekendAttence.setFlag("2");
                // 根据学号以及考勤时间判断考勤表中是否有存在的记录
                List<SdWeekendAttence> attenceList = sdWeekendAttenceDao.getAttenceByDateAndStudentNo(accessDate,weekendAttence.getStudentNo());
    
                if(attenceList == null || attenceList.size() < 1) {
                    sdWeekendAttences.add(weekendAttence);
                    log.info("=====> 正常打卡，结束...");
                }else {
                    log.info("=====> 数据库中存在当前学生当日已打卡记录，结束...");
                }
            }
        
        }
        log.info("数据总量：" + records.size());
        if(sdAttendanceList.size() <= 0){
            log.info("宿舍晚考勤无可匹配数据");
            log.info("......end......");
        }  else {
            boolean b = this.saveBatch(sdAttendanceList);
            long end = System.currentTimeMillis();
            log.info("成功数据：" + sdAttendanceList.size());
            log.info("执行时长：" + (end - begin) + "毫秒。");
            log.info("......end......");
            return b;
        }
        
        if(sdWeekendAttences.size() <= 0) {
            log.info("周末到校考勤无可匹配数据");
            log.info("......end......");
        } else {
            for (SdWeekendAttence sdWeekendAttence : sdWeekendAttences) {
                sdWeekendAttenceDao.insert(sdWeekendAttence);
            }
        }
        return true;
    }
    
    private void pushWxMessageToParent(BStudent student, SdAttence sdAttence) {
            String url = "pages_duty/parent/goOutDetail?studentId="+student.getStudentNo()+
                "&faceTime="+sdAttence.getCreateTime()+"&type=dormitory";
			// 发送模板消息
			Map<String, Object> weatherDataMap = weatherDataCreator.createDormitoryClockRecordDataMap(student.getStudentName(),
					student.getDormitoryNo(), DateUtil.formatDate(sdAttence.getAccessDate()));
			JSONObject jsonObject = wxUtil.sendInfo(student.getParentWxOpenId(), dormitory_clock_template_id
					, weatherDataMap, url);
	
			WechatPushMessage wechatPushMessage = new WechatPushMessage();
			wechatPushMessage.setTemplateId(dormitory_clock_template_id);
			wechatPushMessage.setContent(weatherDataMap.toString());
			wechatPushMessage.setReceiverOpenId(student.getParentWxOpenId());
	
			if (jsonObject != null && "0".equals(jsonObject.get("errcode").toString())) {
				// 发送成功
				wechatPushMessage.setStatus(true);
		
			} else {
				wechatPushMessage.setStatus(false);
			}
			wechatPushMessage.setBackInfo(jsonObject.get("errmsg").toString());
			wechatPushMessageMapper.insert(wechatPushMessage);
    }
    
    /**
     *
     * @param targetTime 目标时间(yyyy-MM-dd HH:mm:ss)
     * @param start 起始时间(HH:mm)
     * @param end 结束时间(HH:mm)
     * @return
     * @throws Exception
     */
    private String judgeAttendanceStatus(String targetTime,String start,String end, String weekendStartTime, String weekendEndTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder startTime = new StringBuilder(targetTime.split(" ")[0]);
        startTime.append(" ").append(start).append(":00");
        StringBuilder endTime = new StringBuilder(targetTime.split(" ")[0]);
        endTime.append(" ").append(end).append(":00");
    
        StringBuilder weekendStart = new StringBuilder(targetTime.split(" ")[0]);
        weekendStart.append(" ").append(weekendStartTime).append(":00");
        StringBuilder weekendEnd = new StringBuilder(targetTime.split(" ")[0]);
        weekendEnd.append(" ").append(weekendEndTime).append(":00");
        long targetMilliseconds = 0;
        long startMilliseconds = 0;
        long endMilliseconds = 0;
        
        long weekendStartMilliSeconds = 0;
        long weekendEndMilliSeconds = 0;
        try {
            targetMilliseconds = sdf.parse(targetTime).getTime();
            startMilliseconds = sdf.parse(startTime.toString()).getTime();
            endMilliseconds = sdf.parse(endTime.toString()).getTime();
    
            weekendStartMilliSeconds = sdf.parse(weekendStart.toString()).getTime();
            weekendEndMilliSeconds = sdf.parse(weekendEnd.toString()).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 晚上考勤
        if(targetMilliseconds >= startMilliseconds && targetMilliseconds <= endMilliseconds){
            return "1";
            // 周末考勤
        }else if(targetMilliseconds >= weekendStartMilliSeconds && targetMilliseconds <= (weekendEndMilliSeconds)){
            return "2";
        }else {
            return "-1";
        }
    }
    
    @Override
    public void deleteDormitoryLeaveAttenceInfo(String studentNo, String startDate, String endDate) {
        sdAttenceDao.deleteDormitoryLeaveAttenceInfo(studentNo, startDate, endDate);
    }
    
    @Override
    public IPage<BStudent> getSdAttenceAbsenceStuPageList(String accessDate, String buildingNo,
                                                          String storey,int pageNum,int pageSize) {
        int startNum = (pageNum - 1) * pageSize;
        List<BStudent> rightData = sdAttenceDao.getSdAttenceStu(accessDate,buildingNo,storey,startNum,pageSize);
        Integer count = sdAttenceDao.getSdAttenceStuCount(accessDate, buildingNo, storey);
        IPage<BStudent> right = new Page<>();
        right.setTotal(count);
        right.setRecords(rightData);
        return right;
    }

    @Override
    public Map<String,Object> getSdAttenceVisualizationData(String accessDate, String buildingNo, String storey,int pageNum,int pageSize) {
        //返回数据
        Map<String,Object> result = new HashMap<>();
        //看板顶部数据
        List<Map<String,Object>> top = new ArrayList<>();
        //看板左边数据
        Map<String,String> left = new LinkedHashMap<>();
        //看板右边数据
        int startNum = (pageNum - 1) * pageSize;
        List<BStudent> rightData = sdAttenceDao.getSdAttenceStu(accessDate,buildingNo,storey,startNum,pageSize);
        Integer count = sdAttenceDao.getSdAttenceStuCount(accessDate, buildingNo, storey);
        IPage<BStudent> right = new Page<>();
        right.setTotal(count);
        right.setRecords(rightData);

        //根据楼栋楼层查询宿舍
        LambdaQueryWrapper<BDormitory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BDormitory::getBuildingNo,buildingNo)
               .eq(BDormitory::getStorey,storey)
                .eq(BDormitory::getStatus,"1")
                .isNotNull(BDormitory::getStuCount).orderByAsc(BDormitory::getDormitoryNo);
        List<BDormitory> dorList = bDormitoryDao.selectList(wrapper);
        //未签到宿舍数量
        int unClockInDor = 0;
        int clockInDor = 0;
        int partClockInDor = 0;

        for (int i = 0; i < dorList.size(); i++) {
            //当前宿舍签到人数
            int clockIn = 0;
            //当前宿舍未签到人数
            int unClockIn = 0;
            //当前宿舍所有学生
            List<BStudent> dorStuList = bStudentDao.getStudentByDormitoryId(dorList.get(i).getId());
            //当前宿舍无学生，则进入下一次循环
            if(dorStuList == null || dorStuList.size() <= 0){
                continue;
            }
            //查询当前宿舍学生是否打卡
            for (int j = 0; j < dorStuList.size(); j++) {
                //未打卡情况：即查询该学生打卡记录的时候为空数据
                List<SdAttence> noClock = sdAttenceDao.getAttenceByDateAndStudentNo(accessDate, dorStuList.get(j).getStudentNo());
                //今天未打卡，则打卡数据为空
                if(noClock == null || noClock.size() <= 0){
                    unClockIn ++;
                //打卡状态为未归寝
                }else if(noClock.get(0).getAttenceStatus().equals("2")){
                    unClockIn ++;
                }else {
                    clockIn ++;
                }
            }

            //判断当前宿舍打卡数量是否和寝室人数一致
            if(unClockIn == dorStuList.size()){
                unClockInDor ++;
                left.put(dorList.get(i).getDormitoryNo(),"1");
            }else if(clockIn == dorStuList.size()){
                clockInDor ++;
                left.put(dorList.get(i).getDormitoryNo(),"2");
            }else if(unClockIn > 0 && clockIn > 0){
                partClockInDor ++;
                left.put(dorList.get(i).getDormitoryNo(),"3");
            }
        }

        //看板顶部数据
        HashMap<String, Object> topData1 = new HashMap<>();
        topData1.put("label","未签到宿舍");
        topData1.put("value",unClockInDor);
        HashMap<String, Object> topData2 = new HashMap<>();
        topData2.put("label","已签到宿舍");
        topData2.put("value",clockInDor);
        HashMap<String, Object> topData3 = new HashMap<>();
        topData3.put("label","部分签到宿舍");
        topData3.put("value",partClockInDor);
        top.add(topData1);
        top.add(topData2);
        top.add(topData3);

        result.put("top",top);
        result.put("left",left);
        result.put("right",CommonPage.restPage(right));
        return result;
    }

}
